<template>
  <div>
    <el-dialog
      :title="title"
      v-model="showDialog"
      :before-close="close"
      width="800px"
      top="30px"
      append-to-body
    >
      <!-- S 完善属性 -->
      <el-form
        ref="formRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="文档目录" prop="fileCategoryId">
          <tree-select
            ref="treeSelect"
            v-model:value="ruleForm.fileCategoryId"
            :options="fileCateTree"
            placeholder="请选择"
            :objMap="{
              value: 'id',
              label: 'categoryName',
              children: 'children',
            }"
            @handleNodeClick="handleNodeClick"
            :disabled="_isReUpload"
          />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="ruleForm.title"
            maxlength="64"
            :disabled="_isReUpload"
          />
        </el-form-item>

        <el-form-item label="文档编码" prop="fileCode" class="code">
          <span class="code-head">
            <span v-if="!deptPinyin">-</span>
            <el-tooltip
              v-else
              effect="dark"
              :content="deptPinyin + '-' + ruleForm.fileCode"
              placement="top-start"
            >
              <span class="code-tooltip"> {{ deptPinyin }}-</span>
            </el-tooltip>
          </span>
          <el-input
            v-model="ruleForm.fileCode"
            maxlength="128"
            :disabled="_isReUpload"
          /> </el-form-item
        ><el-form-item label="文档版本号" prop="version">
          <el-input
            v-model="ruleForm.version"
            @input="_accountInput"
            :disabled="_isReUpload"
          />
        </el-form-item>
        <el-form-item label="关键字说明" prop="notes">
          <el-input
            v-model="ruleForm.notes"
            maxlength="64"
            type="textarea"
            :disabled="_isReUpload"
          />
        </el-form-item>

        <el-form-item label="文档摘要" prop="summary">
          <el-input
            v-model="ruleForm.summary"
            maxlength="512"
            type="textarea"
            :disabled="_isReUpload"
          />
        </el-form-item>
        <el-form-item label="选择文档">
          <!-- S 选择文档 -->
          <div class="upload-edit-dialog">
            <el-upload
              ref="uploadRef"
              drag
              :action="uploadSetting.action"
              :multiple="uploadSetting.multiple"
              :limit="uploadSetting.limit || 1"
              :disabled="uploadSetting.disabled"
              :file-list="fileListBack || []"
              :on-remove="
                (file, fileList) => {
                  return handleRemove(file, fileList, uploadSetting)
                }
              "
              :on-success="
                (response, file, fileList) => {
                  return handleSuccess(response, file, fileList, uploadSetting)
                }
              "
              :on-error="
                (response, file, fileList) => {
                  return handleError(response, file, fileList, uploadSetting)
                }
              "
              :on-exceed="
                (file, fileList) => {
                  return handleExceed(file, fileList, uploadSetting)
                }
              "
              :before-upload="
                (file) => {
                  return beforeAvatarUpload(file, uploadSetting)
                }
              "
              :on-preview="
                (file) => {
                  return handlePreview(file, uploadSetting)
                }
              "
              :on-change="
                (file, fileList) => {
                  return handleChange(file, fileList, uploadSetting)
                }
              "
              :on-progress="handleProgress"
              :headers="importHeaders"
              :auto-upload="!uploadSetting.noAutoUpload"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">点击或将文档拖拽到这里上传</div>
              <template #tip>
                <div class="el-upload__tip">
                  <div>
                    {{ uploadSetting.bottomTip }}
                  </div>
                  <div>
                    {{ uploadSetting.bottomTipVideo }}
                  </div>
                </div>
              </template>
            </el-upload>
          </div>
          <!-- E 选择文档 -->
        </el-form-item>
      </el-form>
      <!-- E 完善属性 -->
      <div class="dialog-footer">
        <el-button type="primary" size="small" @click="submit">
          提交
        </el-button>
        <el-button size="small" @click="close">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="editDialog">
import pinyin from 'js-pinyin'
import {
  getFullNamePinYin,
  getFileName,
  checkFile,
  submitForm,
  accountInput,
} from '../index.js'
import { handleTree } from '@/utils'
import {
  preUpload,
  getFileDetailById,
  getCategoryListHasViewAndUpload,
} from '@/api/fileManager'
const route = useRoute()
const store = useStore()
const emits = defineEmits(['getList', 'close', 'update:open'])
const { proxy } = getCurrentInstance()
let fileAll = ref([]) // 上传文档列表
let fileSuccess = ref([]) // 上传文档成功列表
let fileError = ref([]) // 上传文档失败列表
let fileRemove = ref([]) // 上传文档取消列表
let filePending = ref([]) // 上传中文档
const fileCateTree = ref([])

const showDialog = computed({
  get() {
    return props.open
  },
  set(val) {
    emits('update:open', val)
  },
})

onMounted(() => {
  openDialog()
  _getCategoryListHasViewAndUpload()
})
function _getCategoryListHasViewAndUpload() {
  getCategoryListHasViewAndUpload().then((res) => {
    if (res && res.success) {
      fileCateTree.value = handleTree(res.data, 'id')
    }
  })
}
// 获取上传中文档
function getUploadingFiles() {
  let result = []
  let _fileAll = fileAll.value
  let notPending = []
    .concat(fileSuccess.value)
    .concat(fileError.value)
    .concat(fileRemove.value)
  notPending = [...new Set(notPending)]
  for (let i = 0; i < _fileAll.length; i++) {
    let obj = _fileAll[i]
    let uid = obj.uid
    let isExist = false
    for (let j = 0; j < notPending.length; j++) {
      if (notPending[j].uid === uid) {
        isExist = true
        break
      }
    }
    if (!isExist) {
      result.push(obj)
    }
  }
  filePending.value = result
  console.log('上传中文档')
  console.log(filePending.value)
  console.log('上传中文档')
  noneFilePending()
}

function noneFilePending() {
  if (filePending.value.length === 0) {
    setTimeout(() => {
      uploadListClose()
    }, 1000)
  } else {
    store.commit('app/TOGGLE_UPLOADLIST', true)
  }
}

function uploadListClose() {
  store.commit('app/TOGGLE_UPLOADLIST', false)
}

const importHeaders = reactive({
  Authorization: store.state.user.token,
})

const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '文档编辑',
  },
  fileObj: {
    type: Object,
    default: () => {
      return {}
    },
  },
  fileCate: {
    type: Array,
    default: () => {
      return []
    },
  },
  uploadSetting: {
    type: Object,
    default: () => {
      return {}
    },
  },
})

const ruleForm = ref({
  module: '', // 文档大类
  fileCategoryId: '', //文档目录id
  title: '', // 文档名
  fileCode: '', // 文档编码
  version: 'V1.0', // 版本号
  notes: '', //关键字说明
  summary: '', // 文档摘要
})
function _accountInput(val) {
  ruleForm.value.version = accountInput(val)
}
const rules = reactive({
  fileCategoryId: [
    {
      required: true,
      message: '请选择文档目录',
      trigger: 'change',
    },
  ],
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 0, max: 64, message: '长度不能超过64个字符', trigger: 'blur' },
  ],
  fileCode: [
    { required: true, message: '请输入文档编码', trigger: 'blur' },
    { min: 0, max: 128, message: '长度不能超过128个字符', trigger: 'blur' },
  ],
  version: [
    { required: true, message: '请输入文档版本号', trigger: 'blur' },
    { min: 0, max: 20, message: '长度不能超过20个字符', trigger: 'blur' },
  ],
})

const deptName = store.state.user.userInfo.deptName
let deptPinyin = ref('')
if (deptName) {
  deptPinyin.value = pinyin.getCamelChars(deptName)
}
function handleNodeClick(node) {
  const id = node.id
  deptPinyin.value = getFullNamePinYin(id, props.fileCate, deptName)
}

const resFileDetail = ref({})
const fileListBack = ref([])
const _isReUpload = ref(props.disabled)

function openDialog() {
  // 若来自于代办任务页面
  if (route.query.fromView === 'commissionTask') {
    setData(props.fileObj)
  } else {
    let id = props.fileObj.id
    getFileDetailById(id).then((res) => {
      setData(res.data)
    })
  }
}

function setData(data) {
  ruleForm.value = data
  fileChange.value = data.detail
  resFileDetail.value = data.detail
  // 设置上传文档列表和文档名
  props.fileObj['name'] = data.detail.fileName
  fileListBack.value = [props.fileObj]
  // 设置fileCode
  let dept = data.fileCode.split('-')
  let deptPreArr = proxy.$fn.deepClone(dept)
  deptPreArr.pop()
  deptPinyin.value = deptPreArr.join('-')
  ruleForm.value.fileCode = dept[dept.length - 1]
  flag.value = true
  // 设置覆盖过的不能编辑基础信息
  if (data.detail.lastFileId) {
    _isReUpload.value = true
  } else {
    _isReUpload.value = false
  }
}

function close() {
  if (currentFile.value && currentFile.value.percentage !== 100) {
    proxy
      .$confirm('有文档正在上传，返回后将取消上传，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        if (proxy.$refs['uploadRef'] && proxy.$refs['uploadRef'][0].abort) {
          proxy.$refs['uploadRef'][0].abort()
        }
        removeFile(currentFile.value)
        back()
      })
      .catch(() => {})
  } else {
    back()
  }
}

function back() {
  continueUpload()
  props.uploadSetting.fileList = []
  proxy.$refs.formRef.resetFields()
  proxy.$refs.uploadRef.clearFiles()
  //proxy.$refs.treeSelect.clearHandle()
  if (deptName) {
    deptPinyin.value = pinyin.getCamelChars(deptName)
  }
  emits('close')
}

function submit() {
  submitForm(proxy).then((res) => {
    if (res) {
      const file = fileChange.value
      let fileUploadId = currentUploadId.value
      if (!fileUploadId) {
        fileUploadId = file.fileUploadId
      }
      let filePrams = {
        fileName: file.name || file.fileName,
        fileSize: file.size || file.fileSize,
        fileType: getFileName(file.name || file.fileName),
        fileUploadId,
      }
      if (resFileDetail.value.id) {
        filePrams.id = resFileDetail.value.id
      }
      // 文档上传成功需要把返回的数据提交到后台
      let res = {}
      if (JSON.stringify(successFile.value) != '{}') {
        res = successFile.value.response.data
        delete res.id
        filePrams = { ...filePrams, ...res }
      }
      filePrams['status'] = props.fileObj.status || ruleForm.value.detail.status
      ruleForm.value.detail.oldFileUploadId = ruleForm.value.detail.fileUploadId
      ruleForm.value.detail = filePrams
      //ruleForm.value.id = props.fileObj.id
      if (route.query.view) {
        ruleForm.value.id = Number(props.fileObj.mainId)
      }
      // 复制一份防止点击提交下面修改fileCode后界面直接显示完整code的问题
      let ruleFormTemp = proxy.$fn.deepClone(ruleForm.value)
      ruleFormTemp.fileCode = deptPinyin.value + '-' + ruleForm.value.fileCode
      emits('submit', ruleFormTemp)
    }
  })
}
function continueUpload() {
  proxy.$refs['formRef'].resetFields()
}

function handleProgress(evt, file, fileList) {
  setUploadList(file)
}
// 移除一个文档
function removeFile(file) {
  let storeFileList = store.state.upload.uploadList
  delete storeFileList[file.uid]
  store.commit('SET_UPLOADLIST', storeFileList)
}

// 保存所有上传的文档
function setUploadList(file) {
  let storeFileList = store.state.upload.uploadList
  storeFileList[file.uid] = file
  store.commit('SET_UPLOADLIST', storeFileList)
}
function handleRemove(file, fileList, item) {
  fileRemove.value.push(file)
  console.log('fileRemove')
  console.log(fileRemove)
  getUploadingFiles()
  item['value'] = ''
  item['fileList'] = []
  fileListBack.value = []
  flag.value = true
}

const successFile = ref({})
function handleSuccess(res, file, fileList, item) {
  fileSuccess.value.push(file)
  successFile.value = file
  item['fileList'] = [file]
  console.log('fileSuccess')
  console.log(fileSuccess)
  console.log(res)
  getUploadingFiles()
}

function handleError(res, file, fileList, item) {
  fileError.value.push(file)
  console.log('fileError')
  console.log(fileError)
  getUploadingFiles()
}

// 上传文档个数限制超出提示
function handleExceed(file, fileList, item) {
  const limit = item.limit || 1
  if (fileList.length >= limit) {
    proxy.$message.warning(
      '最多上传' + limit + '个文档,请移除多余文档之后再进行上传'
    )
  }
}

// 上传前处理
const currentFile = ref(undefined)
function beforeAvatarUpload(file, item) {
  // 上传前获取文档id
  fileAll.value.push(file)
  console.log('fileAll')
  console.log(fileAll)
  getUploadingFiles()
  return true
}

// 上传前需要获取一个文档id，该事件会触发上传change回调多次，flag限制每次上传只回调一次
const flag = ref(true)
const currentUploadId = ref(undefined)
const fileChange = ref({})
function handleChange(file, item) {
  if (flag.value && file.status === 'ready') {
    const res = checkFile(file.raw, props.uploadSetting, proxy)
    if (!res) {
      proxy.$refs['uploadRef'].clearFiles()
      return
    }
    setCurrentFileAndName(file)
    flag.value = false
    fileChange.value = file
    props.uploadSetting['fileList'] = [file]
    console.log(ruleForm.value)
    // 上传前获取文档id
    preUpload().then((res) => {
      if (res.code === 200) {
        currentUploadId.value = res.data
        props.uploadSetting.action =
          import.meta.env.VITE_APP_BASE_API + '/doc/file/upload/' + res.data
        setTimeout(() => {
          proxy.$refs.uploadRef.submit()
        }, 0)
      }
    })
  }
}

// 设置当前选择文档，并设置文档名
function setCurrentFileAndName(file) {
  currentFile.value = file
  if (currentFile.value && currentFile.value.name) {
    let name = currentFile.value.name
    if (name.indexOf('.') !== -1) {
      ruleForm.value.title = name.split('.')[0]
    } else {
      ruleForm.value.title = name
    }
  }
}

// 点击已上传文档钩子
function handlePreview(file, item) {
  emits('handlePreview', file)
}
</script>
<style lang="scss">
.upload-edit-dialog {
  .el-upload {
    width: 100%;
  }
  .el-upload-dragger {
    width: 100%;
  }
}
</style>
<style scoped lang="scss">
:deep(.el-tree-select) {
  width: 100%;
}
/* .active {
  display: block !important;
}
.uploadingBox {
  display: none;
} */
.code-tooltip {
  max-width: 400px;
  display: block;
  text-overflow: ellipsis;
  overflow: hidden;
}
:deep(.upload-edit-dialog) {
  width: 100%;
}
.demo-ruleForm {
  width: 90%;
  .el-select {
    width: 100%;
  }
  .code {
    .code-head {
      flex: 1;
      width: 100%;
      margin-right: 6px;
      white-space: nowrap;
    }
    :deep(.el-form-item__content) {
      display: flex !important;
      width: 100%;
      flex-wrap: nowrap;
      align-items: center;
      flex: initial;
    }
  }
}
.upload-edit-dialog {
  text-align: center;
}
.visible {
  display: none;
}
.upload-carousel {
  display: flex;
  align-items: center;
  justify-content: center;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin: 45px 0 0 0;
}
</style>
